package com.trt.system.controller;

import com.trt.system.service.IAdminUserService;
import com.trt.api.BaseController;
import com.trt.api.controller.admin.AdminControllerApi;
import com.trt.enums.ResponseStatusEnum;
import com.trt.exception.ApiException;
import com.trt.pojo.AdminUser;
import com.trt.pojo.dto.AdminLoginBO;
import com.trt.pojo.dto.AdminUserBO;
import com.trt.utils.ApiResult;
import com.trt.utils.PagedGridResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * @author tanrentao
 * @date 2021-12-03
 * @desc
 */
@RestController
public class AdminController extends BaseController implements AdminControllerApi {

    @Autowired
    private IAdminUserService adminUserService;

    @Override
    public ApiResult adminUserLogin(AdminLoginBO adminLoginBO, BindingResult result, HttpServletResponse response) {
        // 1.验证BO中的用户名和密码不为空
//        if (result.hasErrors()) {
//            Map<String, String> map = getErrors(result);
//            return ApiResult.errorMap(map);
//        }
        String username = adminLoginBO.getUsername();
        String password = adminLoginBO.getPassword();
        if (StringUtils.isBlank(username)) {
            return ApiResult.errorCustom(ResponseStatusEnum.ADMIN_USERNAME_NULL_ERROR);
        }
        if (StringUtils.isBlank(password)) {
            return ApiResult.errorCustom(ResponseStatusEnum.ADMIN_PASSWORD_NULL_ERROR);
        }

        // 2. 查询admin用户的信息
        AdminUser adminUser = adminUserService.selectAdminUserByUsername(adminLoginBO.getUsername());
        if (adminUser == null) {
            return ApiResult.errorCustom(ResponseStatusEnum.USER_NOT_EXIST_ERROR);
        }

        // 3.判断密码是否匹配
        boolean isPwdMatch = BCrypt.checkpw(adminLoginBO.getPassword(), adminUser.getPassword());
        if (isPwdMatch) {
            doLoginSettings(adminUser, response);
            return ApiResult.success();
        } else {
            return ApiResult.errorCustom(ResponseStatusEnum.ADMIN_NOT_EXIT_ERROR);
        }
    }

    /**
     * 用于admin用户登录过后的基本信息设置
     */
    private void doLoginSettings(AdminUser adminUser, HttpServletResponse response) {
        // 保存token放入到redis中
        String token = UUID.randomUUID().toString();
        redisUtils.set(REDIS_ADMIN_TOKEN + ":" + adminUser.getId(), token);

        // 保存admin登录基本token信息到cookie中
        setCookie(response, "token", token, COOKIE_MONTH);
        setCookie(response, "userId", adminUser.getId(), COOKIE_MONTH);
        setCookie(response, "name", adminUser.getAdminName(), COOKIE_MONTH);
    }

    @Override
    public ApiResult adminUserIsExist(String username) {
        checkAdminUserIsExist(username);
        return ApiResult.success();
    }

    private void checkAdminUserIsExist(String username) {
        AdminUser adminUser = adminUserService.selectAdminUserByUsername(username);
        if (adminUser != null) {
            ApiException.display(ResponseStatusEnum.ADMIN_USERNAME_EXIST_ERROR);
        }
    }

    @Override
    public ApiResult addAdminUser(AdminUserBO adminUserBO) {
        // 1.验证BO中的用户名和密码不为空
        if (StringUtils.isBlank(adminUserBO.getUsername())) {
            return ApiResult.errorCustom(ResponseStatusEnum.ADMIN_USERNAME_NULL_ERROR);
        }
        if (StringUtils.isBlank(adminUserBO.getPassword())) {
            return ApiResult.errorCustom(ResponseStatusEnum.ADMIN_PASSWORD_NULL_ERROR);
        }

        // 2.base64不为空，则代表人脸入库，否则需要用户输入密码和确认密码
        if (StringUtils.isBlank(adminUserBO.getImg64())) {
            if (StringUtils.isBlank(adminUserBO.getAdminName()) || StringUtils.isBlank(adminUserBO.getPassword())) {
                return ApiResult.errorCustom(ResponseStatusEnum.ADMIN_USERNAME_OR_PASSWORD_NULL_ERROR);
            }
        }

        // 3.密码不为空，则必须判断两次输入一致
        if (StringUtils.isNotBlank(adminUserBO.getPassword())) {
            if (!adminUserBO.getPassword().equalsIgnoreCase(adminUserBO.getConfirmPassword())) {
                return ApiResult.errorCustom(ResponseStatusEnum.ADMIN_PASSWORD_ERROR);
            }
        }

        // 4.校验用户名唯一
        checkAdminUserIsExist(adminUserBO.getUsername());

        // 5.存入admin信息
        adminUserService.createAdminUser(adminUserBO);

        return ApiResult.success();
    }

    @Override
    public ApiResult getAdminUserList(Integer page, Integer pageSize) {
        if (page == null) {
            page = COMMON_START_PAGE;
        }
        if (pageSize == null) {
            pageSize = COMMON_PAGE_SIZE;
        }
        PagedGridResult result = adminUserService.selectAdminUserList(page, pageSize);
        return ApiResult.success(result);
    }

    @Override
    public ApiResult adminLogout(String adminUserId, HttpServletResponse response) {
        // 1.从redis中删除admin的会话token
        redisUtils.del(REDIS_ADMIN_TOKEN + ":" + adminUserId);

        // 2.从cookie中清理adming登录的相关信息
        deleteCookie(response, "token");
        deleteCookie(response, "userId");
        deleteCookie(response, "name");
        return ApiResult.success();
    }

    // 谷歌浏览器开启视频调试模式url  chrome://flags/#unsafely-treat-insecure-origin-as-secure
    // http://admin.itttao.com:9090,http://admin.itttao.com



}
